part of shop;

class PostGoodsPage extends StatefulWidget {
  PostGoodsPage({Key? key}) : super(key: key);
  Map infomap = {};
  @override
  State<StatefulWidget> createState() => _PostGoodsPageState();
}

// class CustomFloatingActionButtonLocation extends FloatingActionButtonLocation {
//   FloatingActionButtonLocation location;
//   double offsetX; // X方向的偏移量
//   double offsetY; // Y方向的偏移量
//   CustomFloatingActionButtonLocation(this.location, this.offsetX, this.offsetY);
//
//   @override
//   Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
//     Offset offset = location.getOffset(scaffoldGeometry);
//     return Offset(offset.dx + offsetX, offset.dy + offsetY);
//   }
// }
class _PostGoodsPageState extends State<PostGoodsPage> {
  // //申请相机、相册等权限
  // PermissionUtils ask = new PermissionUtils();
  // ask.requestCameraPermission();
  // ask.requestPhotosPermission();
  // ask.requestStoragePermission();
  final _postname = TextEditingController();
  final _price = TextEditingController();
  final _introduce = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('商品发布'),
      ),
      body: CustomScrollView(scrollDirection: Axis.vertical, slivers: <Widget>[
        SliverList(
            delegate: SliverChildListDelegate([
          Column(children: <Widget>[
            Align(
                child: Padding(
                    padding: const EdgeInsets.all(30),
                    child: Column(
                      children: <Widget>[
                        TextField(
                          maxLines: null,
                          style: TextStyle(fontSize: 25.0, color: Colors.black),
                          controller: _postname,
                          onChanged: (value) => value = _postname.text,
                          keyboardType: TextInputType.text,
                          decoration: const InputDecoration(
                            labelText: "请输入商品名称",
                            // helperText: "商品名",
                            prefixIcon: Icon(Icons.wallet_giftcard),
                          ),
                        ),
                        TextField(
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            // FilteringTextInputFormatter.digitsOnly,//数字，只能是整数
                            FilteringTextInputFormatter.allow(
                                RegExp("[0-9.]")), //数字包括小数
                            //FilteringTextInputFormatter.allow(
                            //RegExp("[a-zA-Z]")), //只允许输入字母
                          ],
                          style: TextStyle(fontSize: 25.0, color: Colors.black),
                          controller: _price,
                          onChanged: (value) => value = _price.text,
                          decoration: const InputDecoration(
                            labelText: "请输入商品价格（单位：元）",
                            // helperText: "价格/元",
                            prefixIcon: Icon(Icons.attach_money),
                          ),
                        ),
                        TextField(
                          maxLines: null,
                          style: TextStyle(fontSize: 25.0, color: Colors.black),
                          controller: _introduce,
                          onChanged: (value) => value = _introduce.text,
                          keyboardType: TextInputType.text,
                          decoration: const InputDecoration(
                            labelText: "请输入商品详情",
                            // helperText: "商品详情",
                            prefixIcon: Icon(Icons.checklist),
                          ),
                        ),
                        ButtonBar(
                          children: <Widget>[
                            ElevatedButton(
                              onPressed: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            ImagePickerPage()));
                              },
                              // child: new Padding(padding: new EdgeInsets.fromLTRB(50.0, 90.0, 5.0, 100.0)),
                              child: Text("相机拍摄"),
                            ),
                            ElevatedButton(
                              onPressed: () {
                                Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            ChoosePicturePage()));
                              },
                              child: Text("图库上传"),
                            ),
                            FutureBuilder(
                                future:
                                    User._cache?.getLocalInfo().then((value) {
                                  widget.infomap = json.decode(value)
                                      as Map<String, dynamic>;
                                }),
                                builder: (BuildContext context,
                                    AsyncSnapshot<dynamic> snapshot) {
                                  return ElevatedButton(
                                    onPressed: () async {
                                      SharedPreferences uPrefs = await SharedPreferences.getInstance();
                                      String? imagepath = uPrefs.getString("coverimgpath");
                                      if(imagepath != null){
                                        String coverimguri = upload(imagepath);
                                        Map<String, dynamic> productmap = {
                                          'product_id':1,
                                          'product_name': _postname.text,
                                          "product_price": _price as double,
                                          'sell_status': 0,
                                          'product_created_time': DateTime.now()
                                              .millisecondsSinceEpoch,
                                          "product_intro": "",
                                          "product_zone": "",
                                          "seller_id":
                                          json.decode(widget.infomap["id"]),
                                          "connection": {"wx":0,"qq":0,"tel":1},
                                          "product_coverimg":[coverimguri],
                                        };
                                        Product.updateProduct(productmap).then((value){
                                          if(value!=200){
                                            print("商品上传有误");
                                          }
                                        });
                                      }
                                    },
                                    child: const Text("完成"),
                                  );
                                })
                          ],
                        )
                      ],
                    )))
          ])
        ]))
      ]),
      // floatingActionButton: FloatingActionButton(
      //   child: Icon(Icons.add),
      //   tooltip: '上传图片',
      //   onPressed: () {
      //     Navigator.push(context,
      //         MaterialPageRoute(builder: (context) => ImagePickerPage()));
      //   },
      // ),
      // children:<Widget>
    );
  }
}

  //Widget img;
  ///从相册或相机获取图片，仅供参考
  // pickImage() async {
  //   Widget img = Text("图片会出现在这里");
  //   final ImagePicker _picker = ImagePicker();
  //   //final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
  //   final XFile? image = await _picker.pickImage(source: ImageSource.camera);
  //   if (image != null) {
  //     try {
  //       var data = await image.readAsBytes();
  //       setState(() {
  //         img = Image.memory(data);
  //       });
  //     } catch (e) {
  //       setState(() {
  //         img = Text(e.toString());
  //       });
  //     }
  //   }
  //   else {
  //     setState(() {
  //       img = const Text("出错了");
  //     });
  //   }
  //   return img;
  // }

